package service

import (
	"admin-system-go/model"
	"admin-system-go/model/do"
	"admin-system-go/model/dto"
	"admin-system-go/repository"
)

type ResourceService interface {
	QueryResource(dto dto.ResourceQueryDTO) model.ResponseEntity
	CreateResource(dto dto.ResourceBaseDTO) model.ResponseEntity
	DelResource(dto dto.ResourceDelDTO) model.ResponseEntity
}

type resourceServiceImpl struct{}

func (resourceService resourceServiceImpl) QueryResource(queryDto dto.ResourceQueryDTO) model.ResponseEntity {
	var resource do.Resource
	_ = repository.Copy(queryDto, &resource)
	var resources []do.Resource
	pageSize := queryDto.PageSize
	pageNo := queryDto.PageNo
	var total int64
	_ = repository.GetDb().Where(&resource).Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&resources)
	var result = make([]dto.ResourceQueryDTO, len(resources))
	if len(resources) != 0 {
		_ = repository.GetDb().Model(&do.Resource{}).Where(&resource).Count(&total)
	}
	_ = repository.CopySlice(resources, result)
	return model.PageEntityModel(result, &model.PageInfo{
		Total:    total,
		PageSize: pageSize,
		PageNo:   pageNo,
	})
}

func (resourceService resourceServiceImpl) CreateResource(createDto dto.ResourceBaseDTO) model.ResponseEntity {
	var resource do.Resource
	_ = repository.Copy(createDto, &resource)
	tx := repository.GetDb().Where(&do.Resource{Name: createDto.Name}).Find(&resource)
	if tx.RowsAffected > 0 {
		return model.FailEntityModel("资源已经存在")
	}
	tx = repository.GetDb().Create(&resource)
	return model.BoolEntityModel(tx.RowsAffected == 1, tx.Error)
}

func (resourceService resourceServiceImpl) DelResource(delDto dto.ResourceDelDTO) model.ResponseEntity {
	tx := repository.GetDb().Delete(&do.Resource{}, delDto.ResourceIds)
	return model.BoolEntityModel(tx.RowsAffected >= 1, tx.Error)
}
